package pro4;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/addCartItem")
public class CartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码为 UTF-8
        request.setCharacterEncoding("UTF-8");

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        double price = Double.parseDouble(request.getParameter("price"));
        String imageUrl = request.getParameter("imageUrl");
        int quantity = 1; // 默认加入购物车数量为1

        HttpSession session = request.getSession();
        List<CartItem> cartItems = (List<CartItem>) session.getAttribute("cartItems");

        if (cartItems == null) {
            cartItems = new ArrayList<>();
        }

        // 从数据库获取真实商品信息（这里模拟）
        Product product = new Product(id, name, price, 100, imageUrl); // stock 设为默认值100

        boolean found = false;
        for (CartItem item : cartItems) {
            if (item.getProduct().getId().equals(id)) {
                int newQty = item.getQuantity() + quantity;
                if (newQty <= item.getProduct().getStock()) {
                    item.setQuantity(newQty);
                } else {
                    item.setQuantity(item.getProduct().getStock());
                }
                found = true;
                break;
            }
        }

        if (!found) {
            cartItems.add(new CartItem(product, Math.min(quantity, product.getStock())));
        }

        session.setAttribute("cartItems", cartItems);
        response.sendRedirect("Ans4/cart.jsp");
    }
}
